import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, getUserInfo } from '@/api/auth'
import { getMenuList } from '@/api/menu'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useMenuStore } from './menu'
import { getInfo } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref<any>({})
  const menuStore = useMenuStore()
  const permissions = ref<string[]>([])

  // 登录
  const loginAction = async (loginForm: any) => {
    try {
      const res = await login(loginForm)
      if (res.code === 200) {
        if (res.data && res.data.token) {
          token.value = res.data.token
          localStorage.setItem('token', res.data.token)
          ElMessage.success('登录成功')
          // 登录成功后，先拉取菜单并注册动态路由，再跳转首页
          await fetchMenuList()
          await getUserInfoAction()
          router.push('/')
        } else {
          ElMessage.error('登录失败：未获取到token')
        }
      } else {
        ElMessage.error(res.message || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error('登录失败')
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      const res = await getInfo()
      if (res.code === 200) {
        userInfo.value = res.data.user
        permissions.value = res.data.permissions || []
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }

  // 拉取菜单
  const fetchMenuList = async () => {
    try {
      const res = await getMenuList()
      if (res.code === 200) {
        menuStore.setMenuList(res.data)
      }
    } catch (error) {
      console.error('获取菜单失败:', error)
    }
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    menuStore.resetMenuList()
    permissions.value = []
    localStorage.removeItem('token')
    router.push('/login')
  }

  return {
    token,
    userInfo,
    permissions,
    loginAction,
    getUserInfoAction,
    fetchMenuList,
    logout
  }
}) 
